/*
 * Copyright (C) 2014 hu
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package com.sentiment.webcollector.fetcher;

import com.sentiment.database.bean.Datum;
import com.sentiment.database.dbUtil.DbCodecDriver;
import com.sentiment.webcollector.model.Links;

/**
 * 爬取过程中，写入爬取历史、网页Content、解析信息的Writer
 *
 * @author hu
 */
public class SegmentWriter {

	DbCodecDriver<Datum> driver;

	public SegmentWriter(DbCodecDriver<Datum> driver) {
		this.driver = driver;
	}

	/**
	 * 写入一条爬取历史记录
	 *
	 * @param fetch
	 *            爬取历史记录（爬取任务)
	 */
	public void wrtieFetch(Datum fetch) throws Exception {
		if (!driver.insertNotExist(fetch)) {
			Datum target = new Datum();
			target.setUpdate("$set", new Datum(fetch.get_id()));
			driver.update(target, fetch);
		}
	}

	public void writeRedirect(String originUrl, String realUrl) throws Exception {
		Datum target = new Datum();
		Datum origin = new Datum();
		origin.setUrl(originUrl);
		target.setUpdate("$set", origin);
		Datum update = new Datum();
		update.setRealUrl(realUrl);
		driver.update(target, update);
	}

	public void wrtieLinks(Links links) throws Exception {
		for (String url : links) {
			Datum datum = new Datum(url, Datum.STATUS_DB_UNFETCHED);
			driver.insert(datum);
		}
	}
}
